package top.asteam.springcloud.service;

import cn.hutool.core.util.IdUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.concurrent.TimeUnit;

/**
 * @Author Rock Wang
 * @Time 2021/4/20
 */
@Service
public class PaymentService {

    //=======  服务降级

    public String paymentInfoOk(Long id) {
        return "线程池：" + Thread.currentThread().getName() + "paymentInfoOk, id :" + id + "\t" + "O(∩_∩)O~";
    }


    @HystrixCommand(fallbackMethod = "paymentInfoTimeOutHandler",commandProperties = {
            @HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value = "3000"),
            @HystrixProperty(name="execution.timeout.enabled",value = "true")
    })
    public String paymentInfoTimeOut(Long id) {

//        int age = 10/0;
        int timeNum =5;
        try {
            TimeUnit.SECONDS.sleep(timeNum);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "线程池：" + Thread.currentThread().getName() + "8001, id :" + id + "\t" + "/(ㄒoㄒ)/~~ + 耗时"+timeNum+"秒钟~";
    }

    public String paymentInfoTimeOutHandler(Long id){

        return "线程池：" + Thread.currentThread().getName() + "8001, id :" + id + "\t" + "o(╥﹏╥)o~~  服务器暂时不可用";
    }


    //======== 服务熔断

    @HystrixCommand(fallbackMethod = "paymentCircuitBreaker_Fallback",commandProperties = {
            @HystrixProperty(name="circuitBreaker.enabled",value = "true"), //是否开启断路器
            @HystrixProperty(name="circuitBreaker.requestVolumeThreshold",value = "10"), //请求次数
            @HystrixProperty(name="circuitBreaker.sleepWindowInMilliseconds",value = "10000"), //时间窗口期
            @HystrixProperty(name="circuitBreaker.errorThresholdPercentage",value = "60") //失败率达到多少后跳闸
    })
    public String paymentCircuitBreaker(@RequestParam Long id) {
        if(id < 0) {
            throw new RuntimeException("******id 不能负数");
        }
        String serialNumber = IdUtil.simpleUUID();

        return Thread.currentThread().getName()+"\t"+"调用成功，流水号: " + serialNumber;
    }
    public String paymentCircuitBreaker_Fallback(@RequestParam Long id) {
        return "id 不能负数，请稍后再试，/(ㄒoㄒ)/~~   id: " +id;
    }


}
